package com.woniuxy.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.annotation.MultiRequestBody;
import com.woniuxy.exception.customException.AddFailedException;
import com.woniuxy.exception.customException.TheAddedHasBeenExist;
import com.woniuxy.resultCode.Result;
import com.woniuxy.system.entity.AssessmentItems;
import com.woniuxy.system.entity.ItemIndi;
import com.woniuxy.system.entity.PerformanceUser;
import com.woniuxy.system.entity.TempType;
import com.woniuxy.system.service.AssessmentItemsService;
import com.woniuxy.system.service.ItemIndiService;
import com.woniuxy.system.service.TempTypeService;
import com.woniuxy.system.view.AssessmentItemsView;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 考核项 前端控制器
 * </p>
 *
 * @author woniuxy
 * @since 2022-06-01
 */
@RestController
@RequestMapping("/system/assessmentItems")
@RequiresAuthentication
@Slf4j
public class AssessmentItemsController {
    @Autowired
    AssessmentItemsService assessmentItemsService;

    @Autowired
    ItemIndiService itemIndiService;

    @Autowired
    TempTypeService tempTypeService;

    @ApiOperation("获取考核项")
    @PostMapping("/list")
    Result getAssessmentItemsList(@RequestBody(required = false) AssessmentItemsView assessmentItemsView){
//        log.info("获参数assessmentIndicatorView:{}",assessmentItemsView);
        QueryWrapper<AssessmentItems> wrapper = getWrapper(assessmentItemsView);
        Page<AssessmentItems> page=new Page<>(assessmentItemsView.getCurrentPage(),assessmentItemsView.getPageSize());
        Page<AssessmentItems> result = assessmentItemsService.getAllAssessmentItems(page, wrapper);
        return Result.ok().data("msg",result.getRecords()).data("total",result.getTotal()).data("totalPages",result.getPages());
    }
    //封装queryWrapper
    private QueryWrapper<AssessmentItems> getWrapper(AssessmentItemsView assessmentItemsView){
        QueryWrapper<AssessmentItems> queryWrapper=new QueryWrapper<>();
        if(assessmentItemsView!=null){
            if(StringUtils.isNotBlank(assessmentItemsView.getIndicatorId())){
                queryWrapper.eq("acin.id",assessmentItemsView.getIndicatorId()) ;}
            if(StringUtils.isNotBlank(assessmentItemsView.getCycleId())){
                queryWrapper.eq("ai.cycle_id",assessmentItemsView.getCycleId()) ; }
            if(StringUtils.isNotBlank(assessmentItemsView.getName())){
                queryWrapper.like("ai.name",assessmentItemsView.getName()) ; }
        }
        return queryWrapper;
    }

    @PostMapping("/add")
    @RequiresRoles(value={"1","2","3"},logical = Logical.OR)
    Result addAssessmentItems(@MultiRequestBody AssessmentItems assessmentItems ,@MultiRequestBody String indicatorId,@MultiRequestBody String userid) throws TheAddedHasBeenExist {
//        log.info("获取assessmentItems：{}，indicatorId：{}，userid：{} ",assessmentItems,indicatorId,userid);
        boolean b = false;
        if(!(StringUtils.checkValNull(assessmentItems.getName())||StringUtils.checkValNull(assessmentItems.getCycleId())||StringUtils.checkValNull(assessmentItems.getDepartmentId())
                ||StringUtils.checkValNull(assessmentItems.getWeight())||StringUtils.checkValNull(assessmentItems.getDatafromId())||StringUtils.checkValNull(indicatorId))){
                b = assessmentItemsService.addAssessmentItem(assessmentItems, indicatorId, userid);
        }
        if(b){
            return Result.ok();
        }
        return  Result.error().message("添加失败");
    }

    @DeleteMapping("/delete/{id}")
    @RequiresRoles(value={"1","2","3"},logical = Logical.OR)
    Result delete(@PathVariable Long id){
        boolean b = assessmentItemsService.removeById(id);
        QueryWrapper<ItemIndi> itemIndiQueryWrapper = new QueryWrapper<>();
        itemIndiQueryWrapper.eq("item_id",id);
        boolean remove = itemIndiService.remove(itemIndiQueryWrapper);
        if(b&&remove){
            return Result.ok().message("删除成功");
        }
        return Result.error().message("删除失败");
    }

    @ApiOperation(value = "考核模板获取考核项信息")
    @PostMapping("/getTemplateItem")
    @Transactional
    @RequiresRoles(value={"1","2","3"},logical = Logical.OR)
    Result getTemplateItem(@MultiRequestBody  ArrayList<List<String>> item,@MultiRequestBody(required = false) Long Id) throws AddFailedException, TheAddedHasBeenExist {
        for (int i = 0; i <item.size() ; i++) {
                List<String> list = item.get(i);
                TempType tempType = new TempType();
                tempType.setTypeId(Long.valueOf(list.get(0)));
                tempType.setIndicatorId(Long.valueOf(list.get(1)));
                tempType.setItemId(Long.valueOf(list.get(2)));
                tempType.setId(Id);
            LambdaQueryWrapper<TempType> tempTypeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            tempTypeLambdaQueryWrapper.eq(TempType::getId,Id).eq(TempType::getIndicatorId,tempType.getIndicatorId());
            List<TempType> list1 = tempTypeService.list(tempTypeLambdaQueryWrapper);
            if(list1.size()==1){
                throw new TheAddedHasBeenExist();
            }

                boolean save = tempTypeService.save(tempType);
                if(!save){
                    throw new AddFailedException();
                }


        }
        return Result.ok();
    }
}

